import Vue from 'vue'
import Vuex from 'vuex'
import {userLogin, getInfo, getMenu as getUserMenu} from "../api/user";
import {removeToken, setToken} from "../uilts/token";

Vue.use(Vuex)
const store = new Vuex.Store({
    namespaced: true,
    state: {    //共享值
        userinfo: {},
        userMenu: [],
    },
    mutations: {
        //变更操作
        SET_USERINFO(state, info) {
            state.userinfo = info
        },
        SET_USERMENU(state, menu) {
            state.userMenu = menu.data.data
        },
        REST_USER(state) {
            state.userinfo = {}
            state.userMenu = []
        },
    },
    actions: {
        //变更提交
        //第一个参数是Vuex自己，第二个是传过来的参数
        //调用mutations里的SET_NAME方法
        // info(ctx, n) {
        //     ctx.commit('SET_USERINFO', n)
        // }
        login(ctx, userinfo) {
            return new Promise(async resolve => {
                const {data} = await userLogin(userinfo)
                setToken(data.data.token)
                resolve()
            })
        },
        getUserInfo({commit}) {
            return new Promise(async resolve => {
                const info = await getInfo()
                commit('SET_USERINFO', info)
                resolve()
            })
        },
        getMenu({commit}) {
            return new Promise(async resolve => { //异步等待
                const res = await getUserMenu()
                commit('SET_USERMENU', res)
                resolve()
            })
        },
        logout({commit}) {
            return new Promise(async resolve => {
                //退出登录要调接口
                //移除token 清空vuex
                removeToken()
                commit('REST_USER')
                resolve()
            })
        }
    }
})
export default store